package com.pktechan.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pktechan.api.base.BaseMapper;
import com.pktechan.api.base.BaseServiceImpl;
import com.pktechan.api.dao.CustBaseMapper;
import com.pktechan.api.entity.CustBase;
import com.pktechan.api.entity.RealNameInfoLog;
import com.pktechan.api.enumeration.IdCardVerificationResultEnum;
import com.pktechan.api.exception.CustomException;
import com.pktechan.api.service.*;
import com.pktechan.api.utils.EmojiFilter;
import com.pktechan.api.utils.StringUtil;
import com.pktechan.api.vo.ReferencesVO;
import com.pktechan.api.vo.SalesCenterVO;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.faceid.v20180301.FaceidClient;
import com.tencentcloudapi.faceid.v20180301.models.IdCardVerificationRequest;
import com.tencentcloudapi.faceid.v20180301.models.IdCardVerificationResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service("custBaseService")
@Transactional
public class CustBaseServiceImpl extends BaseServiceImpl<CustBase> implements CustBaseService {

    private static final Logger logger = LoggerFactory.getLogger(CustBaseServiceImpl.class);

    @Autowired
    private CustBaseMapper custBaseMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CommissionBalanceService commissionBalanceService;
    @Autowired
    private MsgCodeService msgCodeService;
    @Autowired
    private RealNameInfoLogService realNameInfoLogService;
    @Autowired
    private SendMessageService sendMessageService;

    @Value("${send-msg.secret-id}")
    private String secretId;
    @Value("${send-msg.secret-key}")
    private String secretKey;

    @Value("${send-msg.endpoint}")
    private String endpoint;

    /**
     * 由业务类实现
     *
     * @return
     */
    @Override
    public BaseMapper<CustBase> getBaseMapper() {
        return custBaseMapper;
    }

    /**
     * 保存或更新
     *
     * @param decryptDataJO
     * @param mpId
     */
    @Override
    public void saveOrUpdate4MiniProgram(JSONObject decryptDataJO, String mpId) {

        CustBase custBase = custBaseMapper.getByOpenId(decryptDataJO.getString("openId"));
        if (custBase == null) {
            custBase = new CustBase();
        }
        custBase.setOpenId(decryptDataJO.getString("openId"));
        custBase.setNickname(EmojiFilter.filterEmoji(decryptDataJO.getString("nickName")));
        custBase.setSex(decryptDataJO.getInteger("gender"));
        custBase.setLanguage(decryptDataJO.getString("language"));
        custBase.setCity(decryptDataJO.getString("city"));
        custBase.setProvince(decryptDataJO.getString("province"));
        custBase.setCountry(decryptDataJO.getString("country"));
        custBase.setHeadImgUrl(decryptDataJO.getString("avatarUrl"));
        if (decryptDataJO.containsKey("unionid")) {
            custBase.setUnionId(decryptDataJO.getString("unionId"));
        }
        custBase.setMpId(mpId);
        if (custBase.getId() != null) {
            //更新基本信息
            custBaseMapper.update(custBase);
        }
        redisService.setCustBaseByOpenId(custBase.getOpenId(), JSONObject.toJSONString(custBase));
    }

    /**
     * 注册账户信息
     *
     * @param custBase
     */
    @Override
    public CustBase registration(CustBase custBase, String code) {
        //根据手机号查询当前用户是否注册
        CustBase custBaseByMobile = custBaseMapper.getByMobile(custBase.getMobile());
        if (custBaseByMobile != null) {
            throw new CustomException("当前手机号已被绑定,请更换手机号。");
        }
        //根据手机号获取验证码
        String msgCode = redisService.getMsgCode(custBase.getMobile());
        if (!code.equals(msgCode)) {
            throw new CustomException("验证码错误，请重新输入。");
        }
        //验证码通过,根据手机号删除redis中对应验证码
        redisService.delMsgCode(custBase.getMobile());
        //根据手机号与验证码更改验证码表状态
        msgCodeService.updateMessageCode(custBase.getMobile(), code);

        /**
         * 2024-4-19,取消推荐人的业务逻辑，统一由指定的平台账号完成:888
         *  //根据推荐人id查询推荐人信息
         *         CustBase bbCust = (CustBase) custBaseMapper.getById(custBase.getBbId());
         *         //yy=推荐人.bb
         *         custBase.setYyId(bbCust.getBbId());
         *         //zz = 推荐人.vip_rank=30 ? 推荐人ID : 推荐人.zz
         *         if (VipRankTypeEnum.PROVINCE.getCode().equals(bbCust.getVipRank())) {
         *             custBase.setZzId(bbCust.getId());
         *         } else {
         *             custBase.setZzId(bbCust.getZzId());
         *         }
         *         //配送商=推荐人.vip_type=20 ? 推荐人ID : 推荐人.配送商
         *         if (VipTypeEnum.DISTRIBUTOR.getCode().equals(bbCust.getVipType())) {
         *             custBase.setDistributionCenterId(bbCust.getId());
         *         } else {
         *             custBase.setDistributionCenterId(bbCust.getDistributionCenterId());
         *         }
         */
        custBase.setDistributionCenterId(888);
//        custBase.setVipType(VipTypeEnum.TOURIST.getCode());
//        custBase.setVipRank(VipRankTypeEnum.TOWNSHIP.getCode());
        custBase.setVipType(0);//默认游客
        custBase.setVipRank(0);//默认为最低等级
        custBaseMapper.save(custBase);
        redisService.setCustBaseByOpenId(custBase.getOpenId(), JSONObject.toJSONString(custBase));
        //会员绑定成功通知
        /**
         * 2024-4-19 activeMQ有漏洞，已取消使用
         *         CustomerBindingSuccessMessage customerBindingSuccessMessage = sendMessageService.getCustomerBindingSuccessMessage(custBase.getId());
         *         customerBindingSuccessMessage.setBindingTime(DateUtil.getCurrDateTime());
         *         SendMiniMessageStrategy customerBindingSuccessStrategy = BaseSendMiniMessage.getSendMiniMessage(SendMiniMessageEnum.CUSTOMER_BINDING_SUCCESS);
         *         customerBindingSuccessStrategy.sendMiniMessageToActiveMq(customerBindingSuccessMessage);
         */

        return custBase;
    }

    /**
     * 获取销售中心详情
     *
     * @param custId
     * @return
     */
    @Override
    public SalesCenterVO getSalesCenterDetail(Integer custId) {
        logger.info("根据cust_Id=" + custId + "查询信息");
        CustBase custBase = getById(custId);
        logger.info("获取销售中心佣金信息");
        SalesCenterVO salesCenterVO = commissionBalanceService.getSalesCenterDetail(custBase);
        logger.info("获取bb_id=" + custId + "的直接推荐人信息");
        List<ReferencesVO> firstLevelCustList = custBaseMapper.getFirstLevelCustList(custId);
        salesCenterVO.setDirectReferencesList(firstLevelCustList);
        salesCenterVO.setDirectReferencesNumber(firstLevelCustList.size());
        logger.info("获取bb_id=" + custId + "的间接推荐人信息");
        List<ReferencesVO> secondLevelCustList = custBaseMapper.getSecondLevelCustList(custId);
        salesCenterVO.setIndirectReferencesList(secondLevelCustList);
        salesCenterVO.setIndirectReferencesNumber(secondLevelCustList.size());
        logger.info("获取custId=" + custId + "的下的成员");
        List<ReferencesVO> memberCount = custBaseMapper.getMemberCount(custId);
        salesCenterVO.setMemberCountList(memberCount);
        return salesCenterVO;
    }

    @Override
    public CustBase getCustBaseByUserLoginState(String userLoginState) {
        logger.debug("userLoginState-----debug--" + userLoginState);
        CustBase custBase = new CustBase();
        //获取用户登录信息
        HashMap<String, String> loginStateMap = (HashMap<String, String>) redisService.getLoginState(userLoginState);
        if (loginStateMap != null && loginStateMap.containsKey("openid")) {
            String openId = loginStateMap.get("openid");
            logger.debug("用户openId：" + openId);
            String unionId = loginStateMap.get("unionid");
            custBase = custBaseMapper.getByOpenId(openId);
            if (custBase == null) {
                logger.debug("有未注册（cust_base表无记录）进系统，用户openId：" + openId + "--------unionId：" + unionId);
                custBase = JSONObject.parseObject(redisService.getCustBaseByOpenId(openId), CustBase.class);
            } else {
                logger.debug("登录系统，用户openId：" + openId + "--------unionId：" + unionId);
                redisService.setCustBaseByOpenId(openId, JSONObject.toJSONString(custBase));
            }
        } else {
            logger.debug("参数不合法，非法调用接口");
            throw new CustomException("参数不合法，非法调用接口");
        }
        return custBase;
    }

    /**
     * 获取直接推荐人信息
     *
     * @param custId
     * @return
     */
    @Override
    public List<ReferencesVO> getDirectReferencesDetail(Integer custId) {
        List<ReferencesVO> firstLevelCustDetailList = custBaseMapper.getFirstLevelCustDetailList(custId);
        return firstLevelCustDetailList;
    }

    /**
     * 根据微信openId查询客户基本信息
     *
     * @param openId
     * @return
     */
    @Override
    public CustBase getByOpenId(String openId) {
        return custBaseMapper.getByOpenId(openId);
    }

    /**
     * 实名认证
     *
     * @param custBase
     * @param imageCode
     */
    @Override
    public void realNameAuth(CustBase custBase, String imageCode) {
        logger.debug("实名认证");
        try {
            Credential cred = new Credential(secretId, secretKey);

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("faceid.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            FaceidClient client = new FaceidClient(cred, "", clientProfile);

            IdCardVerificationRequest req = new IdCardVerificationRequest();
            req.setIdCard(custBase.getCertCode());
            req.setName(custBase.getName());

            IdCardVerificationResponse resp = client.IdCardVerification(req);
            logger.debug("实名认证结果，custBase phone:" + custBase.getMobile() + "---resp：" + IdCardVerificationResponse.toJsonString(resp));
            if (!StringUtil.equals(IdCardVerificationResultEnum.SUCCESS.getCode(), resp.getResult())) {
                throw new CustomException(resp.getDescription());
            }
            //实名
            custBaseMapper.update(custBase);
            //保存实名日志
            RealNameInfoLog realNameInfoLog = new RealNameInfoLog();
            realNameInfoLog.setCustId(custBase.getId());
            realNameInfoLog.setOpenId(custBase.getOpenId());
            realNameInfoLog.setType(1);
            realNameInfoLog.setIdCard(custBase.getCertCode());
            realNameInfoLog.setName(custBase.getName());
            realNameInfoLog.setMobile(custBase.getMobile());
            realNameInfoLog.setRequestId(resp.getRequestId());
            realNameInfoLog.setResult(resp.getResult());
            realNameInfoLog.setDescription(resp.getDescription());
            realNameInfoLogService.save(realNameInfoLog);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            throw new CustomException(e.getMessage());
        }
    }
}
